package com.xiubai.appforpda.activitys;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.decoding.Intents;
import com.xiubai.appforpda.R;
import com.xiubai.appforpda.adapter.GetUseAdapter;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.BaseEntity;
import com.xiubai.appforpda.entity.MYSQLNCReturnBean;
import com.xiubai.appforpda.entity.SQLDevicesReturnBean;
import com.xiubai.appforpda.entity.SQLNCGetUseBean;
import com.xiubai.appforpda.entity.SQLOrgPersonBean;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.DateUtils;
import com.xiubai.appforpda.jack.utils.JsonParser;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.jack.utils.WebServiceDataUtils;
import com.xiubai.appforpda.nfc.NfcUtil;
import com.xiubai.appforpda.utils.ClickUtil;
import com.xiubai.appforpda.utils.DisplayUtil;
import com.xiubai.appforpda.utils.NfcUtils;
import com.xiubai.appforpda.utils.ScreenUtils;
import com.xiubai.appforpda.webutils.WebServiceHelper;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;
import com.xiubai.appforpda.widget.pull.PullToRefreshView;

import org.ksoap2.serialization.SoapObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;

import static com.xiubai.appforpda.activitys.MainActivity.REQUEST_CAMERA_PERM;
import static com.xiubai.appforpda.activitys.MainActivity.REQUEST_CODE;

public class GetUseActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemLongClickListener {

    private View btn_setting;
    private View btn_test;
    private PullToRefreshView lv_content;
    private TextView tv_name;
    private View btn_the_user;
    private View btn_scan;
    private String result;
    private boolean is_have = false;
    private GetUseAdapter getUseAdapter;
    private CustomDialog successDialog;
    private boolean first = true;
    private ArrayList<SQLNCGetUseBean> testBeans = new ArrayList<>();
    private View btn_back;
    private View btn_continue_scan;
    private TextView tv_in_name;
    private CustomDialog scanDialog;

    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private NdefMessage mNdefPushMessage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_getuse_promt);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_name.setText("经办人: " + AppConstants.USER_NAME);
        btn_scan = findViewById(R.id.btn_scan);
        btn_scan.setOnClickListener(this);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);

        initNfc();

    }

    private void initNfc() {
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
//            finish();
            return;
        }

        mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mNdefPushMessage = new NdefMessage(new NdefRecord[] {NfcUtil.newTextRecord(
                "Message from NFC Reader :-)", Locale.ENGLISH, true) });
    }

    private void initPromt() {
        if (first) {
            setContentView(R.layout.activity_getuse);
            initView();
            initData();
            first = false;
        } else {
            addData();
        }
    }


    private void initData() {
        testBeans.clear();
        getUseAdapter = new GetUseAdapter(this, testBeans);
        lv_content.setAdapter(getUseAdapter);

        addData();

        /*//必须先初始化
        DatabaseUtils.initHelper(this, "user.db");

        TestBean tb = new TestBean();
        //保存到数据库
        DatabaseUtils.getHelper().save(tb);*/
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final SQLNCGetUseBean item = (SQLNCGetUseBean) parent.getAdapter().getItem(position);
        if (item == null) {
            return true;
        }

        showSuccessDialog("需要删除此条记录吗?", "确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ClickUtil.isFastDoubleClick()) {
                    return;
                }
                dialogDismiss(successDialog);
                testBeans.remove(item);
                getUseAdapter.notifyDataSetChanged();
            }
        });
        return true;
    }

    private void addData() {
        List<SQLNCGetUseBean> beans = DatabaseUtils.getHelper().queryAll(SQLNCGetUseBean.class);
        if (beans != null) {
            for (SQLNCGetUseBean child : beans) {
                if (!is_have) {
                    if (child.pamcode.equals(result)) {
                        SQLNCGetUseBean testBean = new SQLNCGetUseBean();
                        testBean.pamcode = child.pamcode;
                        Trace.d(">>>>" + child.pamcode + testBeans.size());
                        testBean.usercode = child.usercode;
                        testBean.billcode = child.billcode;
                        if (!testBeans.contains(testBean)) {
                            testBeans.add(testBean);
                        }
                        is_have = true;
                    }
                }
            }
        }
        if (!is_have) {
            dialogDismiss(successDialog);
            showSuccessDialog("不属于本次领用范围", "继续", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(ClickUtil.isFastDoubleClick()) {
                        return;
                    }
                    startScan();
                }
            });
            return;
        }
        if (getUseAdapter != null) {
            getUseAdapter.notifyDataSetChanged();
        }
        dialogDismiss(successDialog);
        showSuccessDialog("是否继续扫描", "继续", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ClickUtil.isFastDoubleClick()) {
                    return;
                }
                dialogDismiss(successDialog);
                startScan();
            }
        });

      /*  handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startScan();
            }
        }, 1500);*/
    }

    private static Handler handler = new Handler();

    private void dialogDismiss(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }


    /**
     * 显示抓取成功
     */
    private void showSuccessDialog(String message, String buttonName, View.OnClickListener listener) {
        successDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        successDialog.setView(LayoutInflater.from(this).inflate(R.layout.single_button_layout, null));
        TextView tv_input = (TextView) successDialog.findId(R.id.tv_single_message);
        TextView btn_data_confirm = (TextView) successDialog.findId(R.id.btn_data_confirm);
        View btn_data_return = successDialog.findId(R.id.btn_data_return);
        if (btn_data_return != null) {
            btn_data_return.setVisibility(View.VISIBLE);
            btn_data_return.setOnClickListener(this);
        }
        if (btn_data_confirm != null) {
            btn_data_confirm.setText(buttonName);
            btn_data_confirm.setOnClickListener(listener);
        }
        if (tv_input != null) {
            tv_input.setText(message);
        }
        successDialog.setCanceledOutside(false);
        successDialog.setCancelable(false);
        successDialog.show();

        dialogMatchWindow(successDialog);
    }

    private void dialogWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        int screenWidth = ScreenUtils.getScreenWidth(this);
//        PixelDpHelper.dip2px(this, )
        lp.width = (int) (screenWidth * 0.90f);
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

    private void dialogMatchWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = DisplayUtil.dip2px(300, this.getResources().getDisplayMetrics().density);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

    private void initView() {
        tv_in_name = (TextView) findViewById(R.id.tv_in_name);
        tv_in_name.setText("经办人: " + AppConstants.USER_NAME);
        lv_content = (PullToRefreshView) findViewById(R.id.lv_content);
        btn_the_user = findViewById(R.id.btn_the_user);
        btn_the_user.setOnClickListener(this);
        btn_continue_scan = findViewById(R.id.btn_continue_scan);
        btn_continue_scan.setOnClickListener(this);
        lv_content.setOnItemLongClickListener(this);
        findViewById(R.id.btn_the_back).setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        if(ClickUtil.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_the_user:
                doGetUse();
                break;

            case R.id.btn_scan:
                startScan();
                break;

            case R.id.btn_continue_scan:
                startScan();
                break;

            case R.id.btn_data_return:
                dialogDismiss(successDialog);
                break;
            case R.id.btn_user_scan:
                showPromtMessage();
                break;
            case R.id.btn_user_back:
                dialogDismiss(scanDialog);
                break;
            case R.id.btn_back:
            case  R.id.btn_the_back:// 列表增加一个 返回按钮
                finish();
                break;
        }
    }


    //在onNewIntent中处理由NFC设备传递过来的intent
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Trace.d("--------------NFC-------------");
        // 读取
//        processIntent(intent);
        //调用工具方法，读取NFC数据
        try {
            resolveIntent(intent);
        } catch (Throwable e) {
        }
    }

    private List<Tag> mTags = new ArrayList<>();
    public void resolveIntent(Intent intent) {
        mTags.clear();
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type   未知的标签类型
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NfcUtil.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
                mTags.add(tag);
            }
            // 设置视图
//            buildTagViews(msgs);
//            List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);

            String idsDec = NfcUtil.getIdsHex(mTags);//"331880134"
            String str = "getIdsDec="+ idsDec;
            Trace.d(str);

            List<SQLOrgPersonBean> psncode = DatabaseUtils.getHelper().queryByArgs(SQLOrgPersonBean.class, "psncard", idsDec.replace(" ",""));
            if(psncode != null && psncode.size() > 0 ){
                String psncodeStr = "";
                for (SQLOrgPersonBean bean : psncode) {
                    psncodeStr = bean.psncode;
                }
                for (SQLNCGetUseBean bean : testBeans) {
                    DatabaseUtils.getHelper().update(SQLNCGetUseBean.class, "pamcode", bean.pamcode, "my_status", "Y");
                    DatabaseUtils.getHelper().update(SQLNCGetUseBean.class, "pamcode", bean.pamcode, "audtcode", AppConstants.USER_CODE);
                    DatabaseUtils.getHelper().update(SQLNCGetUseBean.class, "pamcode", bean.pamcode, "billdate", DateUtils.getStringDateShort());
                    DatabaseUtils.getHelper().update(SQLNCGetUseBean.class, "pamcode", bean.pamcode, "usercode", psncodeStr);
                }
                showPromtMessage();
            }else{
                Toast.makeText(this, "没有匹配到员工账号!", Toast.LENGTH_SHORT).show();
                dialogDismiss(scanDialog);
                return;
            }

        }

    }

    private void startScan() {
        is_have = false;
        Intent intent4 = new Intent(GetUseActivity.this, CaptureActivity.class);
        startActivityForResult(intent4, REQUEST_CODE);
    }

    /**
     * 提示扫描卡
     */
    private void doGetUse() {
        scanDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        scanDialog.setView(LayoutInflater.from(this).inflate(R.layout.scan_getuse_layout, null));

        View btn_user_scan = scanDialog.findId(R.id.btn_user_scan);
        if (btn_user_scan != null) {
            btn_user_scan.setOnClickListener(this);
        }
        View btn_user_back = scanDialog.findId(R.id.btn_user_back);
        if (btn_user_back != null) {
            btn_user_back.setOnClickListener(this);
        }
        scanDialog.show();
        // 这里应该扫描卡
        dialogWindow(scanDialog);

    }

    private void showPromtMessage() {

        dialogDismiss(scanDialog);
        showSuccessDialog("领用成功");
    }

    /**
     * 显示抓取成功
     */
    private void showSuccessDialog(String message) {
        successDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        successDialog.setView(LayoutInflater.from(this).inflate(R.layout.single_button_layout, null));
        TextView tv_input = (TextView) successDialog.findId(R.id.tv_single_message);
        View btn_data_confirm = successDialog.findId(R.id.btn_data_confirm);
        if (btn_data_confirm != null) {
            btn_data_confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        if (tv_input != null) {
            tv_input.setText(message);
        }
        successDialog.setCanceledOutside(false);
        successDialog.setCancelable(false);
        successDialog.show();

        dialogMatchWindow(successDialog);
    }



    @Override
    protected void onResume() {
        super.onResume();

        if (mAdapter != null) {
            if (!mAdapter.isEnabled()) {
            }
            mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            mAdapter.enableForegroundNdefPush(this, mNdefPushMessage);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAdapter != null) {
            mAdapter.disableForegroundDispatch(this);
            mAdapter.disableForegroundNdefPush(this);
        }
    }


    @Override
    protected void onDestroy() {
        mAdapter = null;
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    result = bundle.getString(CodeUtils.RESULT_STRING);
                    Trace.d("result" + result);
//                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                    initPromt();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(GetUseActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_BACK) {
                    Trace.d("stop");
                }
            }
        } else if (requestCode == REQUEST_CAMERA_PERM) {
            Toast.makeText(this, "从设置页面返回...", Toast.LENGTH_SHORT)
                    .show();
        }
    }


}
